package com.xdl.flytest.util.job;

import com.xdl.flytest.bean.Task;
import com.xdl.flytest.bean.TestCase;
import com.xdl.flytest.bean.TestSuit;
import com.xdl.flytest.dao.TaskMapper;
import jdk.nashorn.internal.scripts.JO;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Auther: 80736
 * @Date: 2019/2/3 17:46
 * @Description:
 */
@Component
public class DatabaseInitJob {
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private QuartzManager quartzManager;

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * spring容器启动以后，首先执行此方法
     * 从数据库中把job加入系统
     */
    @PostConstruct
    public void initDatabaseJob() throws SchedulerException, ClassNotFoundException {
        logger.info("server start init db task from MySQL");
        List<Task> tasks = taskMapper.selectTasks();
        for (Task task : tasks) {
            String jobClass = task.getJobClass();
            if (jobClass.equals("TestSuit")) {
                logger.info(String.format("task init: add testsuit[%s] task from mysql", task.getTaskName()));
                quartzManager.addJob(task, TestSuitJob.class);
            } else if (jobClass.equals("TestCase")) {
                logger.info(String.format("task init: add testcase[%s] task from mysql", task.getTaskName()));
                quartzManager.addJob(task, TestCaseJob.class);
            } else {
                throw new RuntimeException("job class error");
            }
        }
    }
}
